package com.example.show_auto.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 组合配置存储管理类
 */
class CombinationStorage(context: Context) {
    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences("combination_configs", Context.MODE_PRIVATE)
    
    private val gson = Gson()
    private val contextRef = context // 保存context引用，用于动态创建MultiUserDataManager
    
    companion object {
        private const val KEY_COMBINATIONS = "saved_combinations"
    }
    
    /**
     * 动态获取当前用户ID
     */
    private fun getCurrentUserId(): String? {
        val multiUserDataManager = MultiUserDataManager(contextRef)
        return multiUserDataManager.getCurrentUserId()
    }
    
    /**
     * 保存组合配置
     */
    fun saveCombination(combination: SavedCombination) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不保存
        
        // 为组合添加用户ID
        val combinationWithUserId = combination.copy(userId = currentUserId)
        
        // 获取所有组合配置（包括其他用户的）
        val json = sharedPreferences.getString(KEY_COMBINATIONS, null)
        val allCombinations = if (json != null) {
            try {
                val type = object : TypeToken<List<SavedCombination>>() {}.type
                gson.fromJson<List<SavedCombination>>(json, type) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 分离当前用户和其他用户的组合配置
        val otherUsersCombinations = allCombinations.filter { it.userId != currentUserId }
        val currentUserCombinations = allCombinations.filter { it.userId == currentUserId }.toMutableList()
        
        // 如果已存在同地区配置，替换它；否则添加新配置
        val existingIndex = currentUserCombinations.indexOfFirst { it.areaName == combination.areaName }
        if (existingIndex >= 0) {
            currentUserCombinations[existingIndex] = combinationWithUserId
        } else {
            currentUserCombinations.add(combinationWithUserId)
        }
        
        // 合并所有组合配置
        val updatedCombinations = otherUsersCombinations + currentUserCombinations
        
        val updatedJson = gson.toJson(updatedCombinations)
        sharedPreferences.edit().apply {
            putString(KEY_COMBINATIONS, updatedJson)
            apply()
        }
    }
    
    /**
     * 获取所有保存的组合配置
     */
    fun getAllCombinations(): List<SavedCombination> {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return emptyList() // 如果没有当前用户，返回空列表
        
        val json = sharedPreferences.getString(KEY_COMBINATIONS, null)
        return if (json != null) {
            try {
                val type = object : TypeToken<List<SavedCombination>>() {}.type
                val allCombinations = gson.fromJson<List<SavedCombination>>(json, type) ?: emptyList()
                // 只返回当前用户的组合配置
                allCombinations.filter { it.userId == currentUserId }
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
    }
    
    /**
     * 删除组合配置
     */
    fun deleteCombination(combinationId: String) {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不执行删除
        
        val combinations = getAllCombinations().toMutableList()
        combinations.removeAll { it.id == combinationId }
        
        // 获取所有组合配置（包括其他用户的）
        val json = sharedPreferences.getString(KEY_COMBINATIONS, null)
        val allCombinations = if (json != null) {
            try {
                val type = object : TypeToken<List<SavedCombination>>() {}.type
                gson.fromJson<List<SavedCombination>>(json, type) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 保留其他用户的组合配置，只更新当前用户的
        val otherUsersCombinations = allCombinations.filter { it.userId != currentUserId }
        val updatedCombinations = otherUsersCombinations + combinations
        
        val updatedJson = gson.toJson(updatedCombinations)
        sharedPreferences.edit().apply {
            putString(KEY_COMBINATIONS, updatedJson)
            apply()
        }
    }
    
    /**
     * 清空所有组合配置
     */
    fun clearAllCombinations() {
        val currentUserId = getCurrentUserId()
        if (currentUserId == null) return // 如果没有当前用户，不执行清空
        
        // 获取所有组合配置（包括其他用户的）
        val json = sharedPreferences.getString(KEY_COMBINATIONS, null)
        val allCombinations = if (json != null) {
            try {
                val type = object : TypeToken<List<SavedCombination>>() {}.type
                gson.fromJson<List<SavedCombination>>(json, type) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
        
        // 只保留其他用户的组合配置
        val otherUsersCombinations = allCombinations.filter { it.userId != currentUserId }
        
        if (otherUsersCombinations.isEmpty()) {
            // 如果没有其他用户的配置，直接清空
            sharedPreferences.edit().apply {
                remove(KEY_COMBINATIONS)
                apply()
            }
        } else {
            // 保留其他用户的配置
            val updatedJson = gson.toJson(otherUsersCombinations)
            sharedPreferences.edit().apply {
                putString(KEY_COMBINATIONS, updatedJson)
                apply()
            }
        }
    }
}

/**
 * 保存的组合配置数据类
 */
data class SavedCombination(
    val id: String, // 唯一标识符
    val areaName: String, // 区域名称
    val savedTime: Long, // 保存时间
    val chefs: List<SavedChefInfo>, // 厨师信息快照
    val userId: String = "" // 用户唯一标识
)

/**
 * 保存的厨师信息数据类
 */
data class SavedChefInfo(
    val name: String,
    val rarity: Int,
    val area: String,
    val collectionDetails: String,
    val isUltimate: Boolean,
    val critChance: Int,
    val critMaterial: Int,
    val materialGain: Int,
    val baseMeat: Int,
    val baseFish: Int,
    val baseVeg: Int,
    val baseCreation: Int,
    val totalMeat: Int,
    val totalFish: Int,
    val totalVeg: Int,
    val totalCreation: Int,
    val origin: String = "", // 厨师来源
    val redAmberCount: Int = 0 // 红色心法盘数量

) 